<template>
  <div class="shopCar-container">
    <div class="goods-list">
      <div class="mui-card" v-for="item in reverseList" :key="item.id">
        <div class="mui-card-content">
            <!-- 领券区域 -->
          <div class="mui-card-content-inner goods-item">
            <!-- 开关区域 -->
            <mt-switch
              v-model="selectedObj[item.id]"
              @change="changeSelect(item.id, selectedObj[item.id])"
            ></mt-switch>
            <!-- 图片 -->
            <div class="img-con" @click="toGoodsDetail(item.id)">
              <!-- <img :src="item.thumb_path" /> -->
              <img :src="circleUrl + item.img_url" width="100px" />
            </div>
            <!-- 信息区域 -->
            <div class="info">
              <h1>{{ item.title }}</h1>
              <div class="goods-info">
                <span class="price">￥{{ item.sell_price }}</span>
                <!-- countObj[item.id]表示这条商品对应的数量,传给nobox -->
                <nobox
                  :initcount="countObj[item.id]"
                  :id="item.id"
                  :max="item.stock_quantity"
                ></nobox>
                <a href="#" @click.prevent="del(item.id)">删除</a>
                <!-- 因为a链接有默认行为，所以.prevent -->
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="mui-card">
        <div class="mui-card-content">
          <div class="mui-card-content-inner jiesuan">
            <div class="left">
              <p>总计（不含运费）</p>
              <p>
                已勾选商品 <span class="danger">{{ selectedCount }}</span
                >件
              </p>
              <p>
                原总价<span class="danger">￥{{ amount }}</span>&nbsp;
                现总价<span class="danger">￥{{ amount-discountStr.total | Strformat }}</span>&nbsp;
                <span v-if="discountStr.total>0">
                   优惠<span class="danger">￥{{discountStr.total}}</span>
                </span>
              </p>
            </div>
            <mt-button type="danger" @click="createOrderNo">去结算</mt-button>
          </div>
        </div>
      </div>
      <!-- {{JSON.stringify(selectedObj)}} -->
    </div>
  </div>
</template>

<script>
import { Toast } from "mint-ui";
import moment from "moment";
import nobox from "../sub-components/shopcar_nobox.vue";
import { mapGetters, mapMutations } from "vuex";
export default {
  data() {
    return {
      circleUrl: "http://localhost:9528/admin/news_info/downloadPic?img_url=",
      username: "",
      goodslist: [], //商品列表
      selectGoods: [],
      useStatusList:[],
      order_no: "",
    };
  },
  created() {
    if (localStorage.getItem("UserInfo")) {
      this.username = window.JSON.parse(
        localStorage.getItem("UserInfo")
      ).username;
    }
  },
  activated() {
    this.getGoodsList();
  },
  filters:{
    Strformat(value){
      return value.toFixed(2)
    }
  },
  computed: {
    // mapGetters是数据，mapMutations是方法
    ...mapGetters([
      "idstr",
      "countObj",
      "selectedObj",
      "selectedCount",
      "amount",
      "discountStr",
    ]),
    reverseList() {
      return this.goodslist.reverse();
    },
  },
  methods: {
    ...mapMutations(["delFromCart", "changeSelectState"]),
    getGoodsList() {
      if (this.idstr.length <= 0) return;
      // 添加进入数据库中，这样就能保存每个用户的购物车了，因为local每次都会清除，并且只能存一个用户的.
      this.$http
        .get("/getShopcarList", {
          params: {
            // 此处用到了idstr，使得可以与本地内存中的一样
            id: this.idstr,
          },
        })
        .then((res) => {
          if (res.data.errcode === 200) {
            let data = res.data.message;
            this.goodslist = data;
            this.goodslist.forEach((item) => {
              item.number = this.countObj[item.id];
            });
          } else {
            this.goodslist = [];
          }
        });
    },
    toGoodsDetail(id) {
      this.$router.push({
        path: "/idssp/shops/goodsinfo/" + id,
      });
    },
    // 根据vuex的id得到商品后，将商品
    del(id) {
      // 删除商品，根据id在goodslist移除该项
      this.goodslist.some((item, i) => {
        if (item.id == id) {
          this.goodslist.splice(i, 1);
          return true;
        }
      });
      // 本地内存也要根据Id删除商品
      this.delFromCart(id);
    },
    changeSelect(id, select) {
      // 同名可省略
      // 更改开关的状态
      this.changeSelectState({ id, selected: select });
    },
    createOrderNo() {
      let identity = localStorage.getItem("identityResult");
      if (identity == 2) {
        if (this.selectedCount > 0) {
          let order_no = "OD" + moment(new Date()).format("YYYYMMDDHHmmss");
          localStorage.setItem("order_no", order_no);
          this.toBuy(order_no);
        } else {
          Toast("选择商品为空!!!");
        }
      } else {
        Toast("请您先登录账号！！！");
      }
    },
    toBuy(order_no) {
      this.selectGoods = [];
      this.goodslist.forEach((item) => {
        if (this.selectedObj[item.id]) this.selectGoods.push(item);
      });
      //将购物车的商品添加进入订单表里
      let params = {
        username: this.username,
        order_no: order_no,
        status: 0,
        goodslist: this.selectGoods,
      };
      this.$http.post("/addOrder", params).then((res) => {
        if (res.data.errcode === 200) {
          this.$router.push("/idssp/order/confirmOrder");
        } else {
          Toast("操作失败!!!");
        }
      });
    },
  },
  components: {
    nobox,
  },
};
</script>

<style lang="scss" scoped>
.shopCar-container {
  background-color: #eee;
  overflow: hidden;
  .goods-item {
    width: 100%;
    display: flex;
    // justify-content: space-between;
    img {
      margin-left: 5px;
      vertical-align: middle;
      width: 60px;
      height: 60ox;
    }
    h1 {
      font-size: 13px;
    }
    .info {
      margin-left: 5px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .goods-info {
        display: flex;
        // justify-content: space-between;
        // align-items: center;
        .price {
          width: 55px;
          display: block;
          color: red;
          font-weight: bold;
          font-size: 16px;
        }
      }
    }
  }
  .danger {
    color: red;
    font-weight: bold;
    font-size: 16px;
  }
  .jiesuan {
    display: flex;
    justify-content: space-between;
    align-content: center;
  }
}
</style>